<?php
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

class syntax_plugin_bbcodeextensions_q extends DokuWiki_Syntax_Plugin {

    function getType() { return 'formatting'; }
    function getPType() { return 'normal'; }
    function getAllowedTypes() { return array('formatting', 'disabled'); }   
    function getSort() { return 220; }
    function connectTo($mode){
        $this->Lexer->addSpecialPattern('\[q.+?\[/q\]', $mode, 'plugin_bbcodeextensions_q');
    }

    function handle($match, $state, $pos, Doku_Handler $handler) {
		$match= trim(substr($match, 2, -4));
		$arr= explode(']', $match, 2);
		foreach ($arr as &$a) { $a= trim($a); }
		if (preg_match('/^cite=".+?"/', $arr[0])) {
			//$arr[0]= substr($arr[0], 5,-1);
		} else $arr[0]= '';
		$match= $arr;
        switch ($state) {
          case DOKU_LEXER_ENTER :
            return array($state, $match);

          case DOKU_LEXER_UNMATCHED :
            return array($state, $match);

          case DOKU_LEXER_EXIT :
            return array($state, '');
           
           case DOKU_LEXER_SPECIAL :
			return array($state, $match);

        }
        return array();
    }

	function render($mode, Doku_Renderer $renderer, $data) {
		list ($state, $match) = $data;
		switch ($state) {
			case DOKU_LEXER_ENTER :      
			break;

			//case DOKU_LEXER_UNMATCHED :
			case DOKU_LEXER_SPECIAL :
			if(in_array($mode, ['xhtml', 's5'], true)) {
				//$match= $renderer->_xmlEntities($match);
				//$renderer->doc .= print_r($match,true);
				$match[1]= $renderer->_xmlEntities($match[1]);
				$renderer->doc.= <<<EOF
<q {$match[0]}> {$match[1]} </q>
EOF
;
			} else {
				$renderer->doc .= $match;
			}
			
			break;
			
			case DOKU_LEXER_EXIT:
			break;

		}
        return false;
    }
}
